<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card class="box-card">
      <!-- 添加角色按钮 -->
      <el-row :gutter="20">
        <el-col>
          <!-- TODO -->
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表 -->
      <el-table :data="roles" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item1, i1) in scope.row.children" :key="item1.id"
              :class="['v-center', 'bd-bottom', i1 === 0 ? 'bd-top' : '' ]"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag
                  closable @close="deleteRight(scope.row, item1.id)"
                >{{ item1.authName }}</el-tag>
                <i class="el-icon-caret-right"/>
              </el-col>
              <!-- 二级、三级权限 -->
              <el-col :span="19">
                <el-row
                  v-for="(item2, i2) in item1.children" :key="item2.id"
                  :class="['v-center', i2 === 0 ? '' : 'bd-top']"
                >
                  <el-col :span="7">
                    <el-tag type="success"
                      closable @close="deleteRight(scope.row, item2.id)"
                    >{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"/>
                  </el-col>
                  <el-col :span="17">
                    <el-tag type="warning"
                      v-for="item3 in item2.children" :key="item3.id"
                      closable @close="deleteRight(scope.row, item3.id)"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"/>
        <el-table-column label="角色名称" prop="roleName"/>
        <el-table-column label="角色描述" prop="roleDesc"/>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <!-- TODO -->
            <el-button type="primary" size="mini" icon="el-icon-edit">编辑</el-button>
            <!-- TODO -->
            <el-button type="danger" size="mini" icon="el-icon-delete">删除</el-button>
            <el-button type="warning" size="mini" icon="el-icon-setting"
              @click="showSetRightDialog(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 权限分配对话框 -->
    <el-dialog title="权限分配" width="50%"
      :visible.sync="setRightDialogVisible"
      @close="closeSetRightDialog"
    >
      <!-- 树形控件 -->
      <el-tree
        ref="rightTreeRef"
        :data="rightTree"
        :props="rightTreeProps"
        default-expand-all
        show-checkbox
        node-key="id"
        :default-checked-keys="defaultRights"
      />
      <!-- 底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 角色列表
      roles: [],
      // 控制分配权限对话框的显示与隐藏
      setRightDialogVisible: false,
      // 权限树
      rightTree: [],
      rightTreeProps: {
        children: 'children',
        label: 'authName'
      },
      // 默认选中的权限点 id
      defaultRights: [],
      // 当前既将分配权限的角色 id
      roleId: ''
    }
  },
  created () {
    this.getRoles()
  },
  methods: {
    // 获取角色列表
    async getRoles () {
      const { data } = await this.$http.get('roles')
      if (data.meta.status !== 200) {
        return this.$message.error('获取角色列表失败，' + data.meta.msg)
      }
      this.roles = data.data
    },
    // 获取权限树
    async getRightTree () {
      const { data } = await this.$http.get('rights/tree')
      if (data.meta.status !== 200) {
        return this.$message.error('获取权限树失败，' + data.meta.msg)
      }
      this.rightTree = data.data
      console.log(data)
    },
    // 弹框提示是否删除权限
    async deleteRight (role, rightId) {
      const res = await this.$confirm('确认删除该权限？',
        '确认删除', {
          confirmButtonText: '确定',
          calcelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
      if (res !== 'confirm') {
        return this.$message.info('取消删除')
      }
      const { data } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (data.meta.status !== 200) {
        return this.$message.error('删除权限失败，' + data.meta.msg)
      }
      this.$message.success('删除权限成功')
      role.children = data.data
    },
    // 展示分配权限对话框
    showSetRightDialog (role) {
      this.setRightDialogVisible = true
      this.getRightTree()
      this.getDefaultRights(role, this.defaultRights)
      this.roleId = role.id
    },
    // 关闭分配权限对话框
    closeSetRightDialog () {
      this.defaultRights = []
    },
    // 将所有三级权限 id 放入 arr 中
    getDefaultRights (node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      for (let child of node.children) {
        this.getDefaultRights(child, arr)
      }
    },
    // 分配权限对话框点击确定
    async setRights () {
      const ref = this.$refs.rightTreeRef
      const keys = [
        ...ref.getCheckedKeys(),
        ...ref.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      const { data } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (data.meta.status !== 200) {
        return this.$message.error('分配权限失败，' + data.meta.msg)
      }
      this.$message.success('分配权限成功')
      this.getRoles()
      this.setRightDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bd-top {
  border-top: 1px solid #eee;
}
.bd-bottom {
  border-bottom: 1px solid #eee;
}
.v-center {
  display: flex;
  align-items: center;
}
</style>
